/* eslint-disable callback-return */
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'
import {
  ACCESS_TOKEN
} from '@/store/mutationTypes'
import i18n from '@/lang'
import {
  BasicLayout
} from '@/views/layouts'
import {getSSOToken} from '@api/login'
import {Base64EncodedTriggerRule} from "tencentcloud-sdk-nodejs/tencentcloud/apigateway/v20180808/models";
import message from "ant-design-vue/lib/message";
import MyApply from "@api/modules/todo/myApply";
import testRoutes from "@/router/test";

const jwtDecode = require('jwt-decode')
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['login', 'userWelcome', '401', 'userHelpinstructions'];

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (sessionStorage.getItem(ACCESS_TOKEN)=="null"){
    console.debug(sessionStorage.getItem(ACCESS_TOKEN))
    sessionStorage.clear();
  }
  if (whiteList.includes(to.name)) {
    next();
    return;
  }
  if (!sessionStorage.getItem(ACCESS_TOKEN)) {
    hasNoToken(to, next, from)
    return;
  }
  // const data = jwtDecode(sessionStorage.getItem(ACCESS_TOKEN))
  if (store.getters.permissionTags.length === 0) {
    // 登录成功后获取用户信息，路由需要从用户权限信息获取
    store
      .dispatch('GetInfo')
      .then((data) => {
        // 生成路由列表
        if (data.enabled === 2) {
          handleRegister(next, to)
        }else {
          getGenerateRoutes(to, from, next);
          next();
        }
      })
      .catch((e) => {
        hasNoToken(to, next, from)
      })
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
// 无token处理
function hasNoToken (to, next, from) {
  NProgress.done();
  //sso 回调时
  if(to.query.code && to.query.lang){
    sessionStorage.removeItem(ACCESS_TOKEN)
    //带了sso的state值回来
    getSSOToken(to.query.code).then(res => {
      sessionStorage.setItem(ACCESS_TOKEN, res.data.token);
      next({
        path: window.atob(to.query.state)
      });
    });
  }
  else {
    // 其余页面直接进入登录页面
    next({path: `/401?redirect=${to.fullPath}`, query: {
        redirect: to.path, ...to.query
      }})
  }

}


// 生成路由列表
function getGenerateRoutes (to, from, next) {
  console.log(store.getters.addRouters)
  let addRoutersArray = []
  let redirect = '/'
  if (store.getters.addRouters.length) {
    addRoutersArray = store.getters.addRouters
    redirect = store.getters.addRouters[0].path
  }
  const routerTransform = [{
    path: '/',
    name: 'index',
    redirect,
    component: BasicLayout,
    meta: {
      title: 'overview1'
    },
    children: [
      ...addRoutersArray]
  },
  // 所有不正确的路由都匹配404
  {
    path: '*',
    redirect: () => {
      message.warning({ content: i18n.t('dqyhmyshqx'), key: 'redirectOnlyShowOne' })
      return redirect
    }
  },
  // sso 跳转地址，如果动态路由中定义了此路径则按照动态路由中的定义跳转，没有则进入此逻辑
  {
    path: '/dashboard',
    redirect: redirect
  }
  ]
  // 动态添加可访问路由表
  //   resetRouter() // 重置路由，防止在未刷新的情况下报路由重复
  router.addRoutes(routerTransform);
    //初始化路由后，如果带着跳转参数跳转到目标路由
    if (!from.query.redirect) {
      // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      next({
        ...to,
        replace: true
      })
    } else {
      const toUrl = decodeURIComponent(from.query.redirect || to.path)
    // 跳转到目的路由
      next({
        path: toUrl
      })
    }
  // }
}
function handleRegister(next, to) {
  let routes;
    MyApply.getMyApplyList({businessCode: 'user_register'}).then((res) => {
    if (res.totalCount === 0) {
      store.commit('SET_permissionTags', ['register:view'])
      routes = [{
        path: '*',
        redirect: '/register'
      },{
        path: '/register',
        name: 'register',
        component: () => import('@/views/exception/noFunctionalPermissions'),
        meta: {
          title: '注册',
          icon: '',
          affix: true,
          hasChildMenus: false,
          active: true,
          breadList: []
        },
        display: 1
      },
        {
          path: '/user',
          component:  () => import('@/views/layouts/UserLayout'),
          redirect: '/user/welcome',
          hidden: true,
          children: [
            // 用户注册页
            {
              path: '/user/signUp',
              component: () => import('@/views/user/SignUp.vue')
            }
          ]},
        // sso 跳转地址
        {
          path: '/dashboard',
          name: 'dashboard',
          redirect: '/register'
        }];
      store.commit('SET_ROUTERS', [routes[0]]);
    } else {
      // 我的申请
      store.commit('SET_permissionTags', ['todo:own:audit'])
      routes = [
        {
          path: '/',
          name: '',
          redirect: '/todo/myApplication',
          component: BasicLayout,
          meta: {
            title: ''
          },
          display: false,
          children: [
            {
              path: '/todo',
              name: 'todo',
              redirect: '/todo/myApplication',
              component: () => import('@/views/layouts/pageView'),
              meta: {
                title: '我的事项'
              },
              display: true,
              children: [
                {
                  path: '/todo/myApplication',
                  name: 'myApplication',
                  component: () => import('@/views/todo/myApplication'),
                  meta: {
                    title: '我的申请',
                    icon: 'icon-shenqing',
                    affix: true,
                    hasChildMenus: false,
                    active: true,
                    breadList: []
                  },
                  display: true,
                  children:[]
                },
                {
                  path: '/todo/applicationContent',
                  name: 'applicationContent',
                  component: () => import('@/views/todo/myApplication/applicationDetail'),
                  meta: {
                    title: '申请详情',
                    affix: false,
                    hasChildMenus: false,
                    active: true,
                    breadList: []
                  },
                  display: false
                }
              ]
            },
          ]
        },
        // sso 跳转地址
        {
          path: '/dashboard',
          name: 'dashboard',
          redirect: '/todo/myApplication'
        },
        // 所有不正确的路由都匹配404
        {
          path: '*',
          redirect: () => {
            message.warning({ content: i18n.t('dqyhmyshqx'), key: 'redirectOnlyShowOne' })
            return '/dashboard'
          }
        },
      ]
      store.commit('SET_ROUTERS',  routes[0].children);
    }
    store.commit('SET_FIRST_ROUTE', routes[0].path)
    router.addRoutes(routes);
    next(to);
    // next('/dashboard');
  });
}
